package com.bobo.listener;

import com.bobo.service.VoucherService;
import com.rabbitmq.client.Channel;
import com.bobo.entity.Voucher;
import com.bobo.entity.VoucherOrder;
import com.bobo.mapper.VoucherMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.io.IOException;

@Component
@RequiredArgsConstructor
@Slf4j
public class VoucherListener {


    private final VoucherService voucherService;


    /**
     * 优惠券抢购数据库操作监听
     * @param voucherOrder
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "voucher.order",durable = "true"),
            exchange = @Exchange(name = "voucher.direct",durable = "true"),
            key = "voucher.order.create"
    ))
    public void voucher(VoucherOrder voucherOrder) {
        //进行数据库操作，数据库操作内判断幂等性
        voucherService.addVoucherOrder(voucherOrder.getVoucherId(),voucherOrder);
    }

    /**
     * 超时订单监听
     * @param voucherOrder
     */
    @RabbitListener(queues = "voucher.dead.queue")
    public void handleExpiredVoucherOrder(VoucherOrder voucherOrder) {
        //移交impl层去做超时订单处理
        voucherService.expireVoucherOrderHandler(voucherOrder);
    }

}
